package com.baizhi.controller;

import com.baizhi.entrty.Album;
import com.baizhi.service.AlbumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class AlbumController {
    @Autowired
    private AlbumService as;

    @RequestMapping("fyalbum")
    @ResponseBody
    public Map fy(int page, int rows){
        return as.fy(page,rows);
    }

    @RequestMapping("/addAlbum")
    @ResponseBody
    public Map addAlbum(Album album, MultipartFile photo, HttpServletRequest request) throws IOException {

        String originalFileName = photo.getOriginalFilename();

        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        String realPath = request.getServletContext().getRealPath("/img");
        String uuid = UUID.randomUUID().toString();
        String newPhoto = uuid + suffix;

        photo.transferTo(new File(realPath + "/" +newPhoto));

        album.setAlbumImage("/img/"+newPhoto);
        Map map = new HashMap();
        try {
            as.addAlbum(album);
            map.put("myadd",true);
        } catch (Exception e) {
            map.put("myadd",false);
            e.printStackTrace();

        }

        return map;
    }

    @RequestMapping("deleteAlbum")
    @ResponseBody
    public Map delete(int[] id){
        Map map = new HashMap();
        try {
            as.delete(id);
            map.put("mydeleteAlbum",true);
        } catch (Exception e) {
            map.put("mydeleteAlbum",false);
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("updateAlbum")
    @ResponseBody
    public Map update(Album al, MultipartFile photo, HttpServletRequest request) throws IOException {

        String originalFileName = photo.getOriginalFilename();

        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        String realPath = request.getServletContext().getRealPath("/img");
        String uuid = UUID.randomUUID().toString();
        String newPhoto = uuid + suffix;

        photo.transferTo(new File(realPath + "/" +newPhoto));

        al.setAlbumImage("/img/"+newPhoto);

        Map map = new HashMap();

        try {
            System.out.println(al+"-----------");
            System.out.println(al+"-----------");
            System.out.println(al+"-----------");
            as.update(al);
            map.put("myupdateAlbum",true);
        } catch (Exception e) {
            map.put("myupdateAlbum",false);
            e.printStackTrace();
        }
        return map;
    }
}
